﻿/**
* created by zhongrui at 2015.02.11
* jquery.unionSelect.js
*/
; (function ($) {

    $.extend({
        unionSelect: function (options) {
            var defaults = {
                //root: {
                //    selector: "#provinces",//选择符
                //    url: "/Common/GetAreas",//获取选项的url
                //    urlParamName: "parentId",//获取选项的url需要带的参数(可选参数)
                //    urlParamValue: "",//获取选项的url需要的参数的默认值,（可选参数）
                //    selectValue: "c96a7734-5cc1-4fa3-ac26-fcf34017e05e",//测试用默认值，福建，（可选）
                //    //可以递归，子节点
                //    child: {
                //        selector: "#cities",
                //        url: "/Common/GetAreas",
                //        urlParamName: "parentId",//获取选项的url需要带的参数(可选参数)
                //        selectValue: "c5cc824f-7680-4d26-85a6-a3f226cd686e",//测试用默认值，厦门（可选）
                //    }
                //},
                select2Width: "100%",
                useSelect2: false,
                allowEmpty: false,
                passValueToSelector: "",//把整个联动控件的值传递给这个选择符的表单控件
                noPassValueSelectors: [],//在数组里的选择符，值只作为联动使用，不设置到最后元素的name
            };

            var options = $.extend(defaults, options);

            var select2Params = null;
            if (options.useSelect2 || $(options.root.selector).hasClass("select2")) {
                select2Params = { width: options.select2Width };
            }

            ajaxGetOptions(options.root, options.allowEmpty, select2Params, options.passValueToSelector, options.noPassValueSelectors);
        }
    })

    //remote load options
    function ajaxGetOptions(elementOptions, allowEmpty, select2Params, passValueToSelector, noPassValueSelectors) {
        var params = {};
        if (elementOptions.urlParamName) {
            params[elementOptions.urlParamName] = !!elementOptions.urlParamValue
                                                ? elementOptions.urlParamValue
                                                : "";
        }
        $.post(elementOptions.url, params, function (options) {
            if (!options || !options.length) {
                options = [];
            }

            var $currentElement = $(elementOptions.selector);
            $currentElement.html("");//clear old item

            if (allowEmpty) {
                options.unshift({
                    Value: "",
                    Text: "请选择"
                });
            }

            setOptions(elementOptions.selector, options, elementOptions.selectValue, passValueToSelector);
            if (select2Params) {
                $currentElement.select2(select2Params);
            }
            //onchange
            $currentElement.on("change", function () {
                if (passValueToSelector && $.inArray(elementOptions.selector, noPassValueSelectors) == -1) {
                    $(passValueToSelector).val($(this).val());
                }
            });

            if (elementOptions.child) {
                //load child
                if (elementOptions.selectValue && elementOptions.child.selectValue) {
                    elementOptions.child.urlParamValue = elementOptions.selectValue;
                }
                else {
                    elementOptions.child.urlParamValue = $currentElement.val();
                }
                ajaxGetOptions(elementOptions.child, allowEmpty, select2Params, passValueToSelector, noPassValueSelectors);

                //onchange
                $currentElement.on("change", function () {
                    elementOptions.child.urlParamValue = $(this).val();
                    ajaxGetOptions(elementOptions.child, allowEmpty, select2Params, passValueToSelector, noPassValueSelectors);
                });
            }
        });
    }

    //insert options
    function setOptions(seletor, options, selectedValue, passValueToSelector) {
        var htmlStr = '';
        for (var i = 0; i < options.length; i++) {
            var option = options[i];
            var selected = option.Value === selectedValue ? " selected " : "";
            htmlStr += '<option value="' + option.Value + '"' + selected + '>' + option.Text + '</option>';
            if (option.Value === selectedValue) {
                $(passValueToSelector).val(option.Value);
            }
        }
        $(seletor).html(htmlStr);
    }

    jQuery.fn.extend({
        unionselect: jQuery.fn.unionSelect,
        unionselector: jQuery.fn.unionSelect,
        unionSelector: jQuery.fn.unionSelect,
    });
})(jQuery)